package com.jeecg.p3.system.web.back;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.UploadUtil;
import com.jeecg.p3.system.config.UploadConfig;
import com.jeecg.p3.system.entity.Course;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.service.CourseService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @program: jeewx-boot-parent
 * @description: 课程内容控制类
 * @author: binbin
 * @create: 2020-09-28 15:09
 */
@Controller
@RequestMapping("/system/back/course")
public class CourseController extends BaseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private ProductService productService;

    @Autowired
    protected UploadConfig uploadConfig;

    /**
     * 列表页面
     * @return
     */
    @RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
    public void list(@ModelAttribute Course query, HttpServletResponse response, HttpServletRequest request,
                     @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                     @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<Course> pageQuery = new PageQuery<Course>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        pageQuery.setQuery(query);
        velocityContext.put("course",query);
        List<Product> lstProduct = productService.find();
        velocityContext.put("lstProduct",lstProduct);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(courseService.queryPageList(pageQuery)));
        String viewName = "system/back/course-list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 详情
     * @return
     */
    @RequestMapping(value="toDetail",method = RequestMethod.GET)
    public void courseDetail(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/course-detail.vm";
        Course course = courseService.queryById(id);
        velocityContext.put("course",course);
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public void toAddDialog(HttpServletRequest request, HttpServletResponse response, ModelMap model)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        List<Product> lstProduct = productService.find();
        velocityContext.put("lstProduct",lstProduct);
        String viewName = "system/back/course-add.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存信息
     * @return
     */
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doAdd(@ModelAttribute Course course){
        AjaxJson json = new AjaxJson();
        try {
            courseService.doAdd(course);
            json.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            json.setSuccess(false);
            json.setMsg("保存失败");
        }
        return json;
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="toEdit",method = RequestMethod.GET)
    public void toEdit(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        Course course = courseService.queryById(id);
        velocityContext.put("course",course);
        List<Product> lstProduct = productService.find();
        velocityContext.put("lstProduct",lstProduct);
        String viewName = "system/back/course-edit.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute Course course){
        AjaxJson j = new AjaxJson();
        try {
            courseService.doEdit(course);
            j.setMsg("编辑成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }


    /**
     * 删除
     * @return
     */
    @RequestMapping(value="doDelete",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) Long id){
        AjaxJson j = new AjaxJson();
        try {
            Course course = courseService.queryById(id);
            courseService.doDelete(id);
            j.setMsg("删除成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("删除失败");
        }
        return j;
    }


    /**
     * 根据课程id查询课时列表
     * @param productId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="findByProductId",method = RequestMethod.POST)
    public AjaxJson findByProductId(Long productId) {
        AjaxJson j = new AjaxJson();
        List<Course> courses = courseService.listCourseByProductId(productId);
        j.setObj(courses);
        j.setMsg("查询成功！");
        return j;
    }

    /**
     * 微信分享图片上传
     * 保存图片
     * @return
     */
    @RequestMapping(value = "/doUpload",method ={RequestMethod.POST})
    @ResponseBody
    public AjaxJson doUpload(MultipartHttpServletRequest request, HttpServletResponse response, MultipartFile file){
        LoginUser user = (LoginUser) request.getSession().getAttribute(Constants.OPERATE_WEB_LOGIN_USER);
        AjaxJson j = new AjaxJson();
        try {
            String fileUrl =  ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.wxShare;
            String fileDir = uploadConfig.getUploadPath() + user.getId() + ComCode.wxShare;
            if(!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                UploadUtil.createDirectory (fileDir);
                String filePath = fileDir + fileName;
                File newFile = UploadUtil.getAvailableFile (filePath, 0);
                file.transferTo (newFile);
                j.setObj(fileUrl + newFile.getName ());
                j.setMsg("保存成功");
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }
}
